﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Travel.CommonUtil.Snowflake;
using Travel.Data;
using Travel.Data.Dtos;
using Travel.Data.Dtos.TravelBusiness;
using Travel.Data.Entity;
using Travel.Data.Inputs;

namespace Travel.Service.TravelBusiness.Impl
{
    /// <summary>
    /// 订单相关服务
    /// </summary>
    public class OrderService : ServiceBase, IOrderService
    {
        
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Results<string>> OrderAdd(OrderAddInput input)
        {
            //1.检查是否重复下单
            var count = TravelContext.TabOrders.Count(c => !c.Deleted && c.CreatedUserId == input.LoginUserId && c.TravelId == input.TravelId);
            if (count > 0)
            {
                return Results<string>.FailResult("请勿重复下单");
            }
            //2.是否超出人数限制（高并发）
            //2.1查询人数限制
            var travel = await TravelContext.TabTravels.FirstOrDefaultAsync(c => !c.Deleted && c.Id == input.TravelId);
            //2.2查询当前已经下单的人数
            var detail = TravelContext.TabOrderDetails.Where(c => c.TravelId == input.TravelId);
            int currentCount = input.Friends.Count() + 1;
            if (travel.HavaOrdered + currentCount > travel.PersonLimit)
            {
                return Results<string>.FailResult("人数超出限制");
            }
            travel.HavaOrdered += currentCount;
            long orderId = SnowIdWorker.NextId();
            await TravelContext.TabOrders.AddAsync(new Data.Entity.TabOrder()
            {
                TravelId = orderId,
                CreatedUserId = input.LoginUserId,
                UpdatedUserId = input.LoginUserId,
                Id = SnowIdWorker.NextId(),

            });
            if (input.Friends.Any())
            {
                foreach (var item in input.Friends)
                {
                    var detailEntity = new TabOrderDetail()
                    {

                        Id = SnowIdWorker.NextId(),
                        FriendMobile = item.Mobile,
                        FriendName = item.NickName,
                        OrderId = orderId,
                        OrderUserId = input.LoginUserId,
                    };
                    await TravelContext.TabOrderDetails.AddAsync(detailEntity);
                }
            }
            var saved = true;
            var orderdFlag = false;
            while (saved)
            {
                try
                {
                    await TravelContext.SaveChangesAsync();
                    saved = false;
                }
                catch (DbUpdateConcurrencyException e)
                {
                    foreach (var item in e.Entries)
                    {
                        if (item.Entity is TabTravel)
                        {
                            var databaseValues = item.GetDatabaseValues();//出现并发时，数据库中的值
                            var currentValues = item.CurrentValues;//当前实体的值
                            foreach (var property in currentValues.Properties)
                            {
                                if (property.Name == nameof(travel.HavaOrdered))
                                {
                                    var proposedValue = currentValues[property]; //当前实体HaveOrder的值
                                    var databaseValue = databaseValues[property];//数据库中HaveOrder的值
                                    if (Convert.ToInt32(databaseValue) + input.Friends.Count() + 1 > travel.PersonLimit)
                                    {
                                        orderdFlag = false ;
                                        currentValues[property] = databaseValue;
                                    }
                                    else
                                    {
                                        currentValues[property] = Convert.ToInt32(databaseValue) + currentCount;
                                        orderdFlag = true;//标识下单成功
                                    }
                                }
                            }
                            //刷新原始值以绕过下一次并发检查
                            item.OriginalValues.SetValues(databaseValues);
                        }

                    }
                }

            }
            if (orderdFlag)
            {
                return Results<string>.DataResult("下单成功");

            }
            return Results<string>.DataResult("下单失败，人数超出");
        }
        /// <summary>
        /// 订单查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<PageDto<OrderDto>>> OrderQuery(OrderQueryInput input)
        {
            PageDto<OrderDto> result = new();
            var query = from o in TravelContext.TabOrders.AsNoTracking()
                        join t in TravelContext.TabTravels.AsNoTracking() on o.TravelId equals t.Id
                        select new
                        {
                            o.Id,
                            t.TravelName,
                            t.Price,
                            o.CreatedTime,
                            o.CreatedUserId,//下单人ID
                            SellerUserId = t.CreatedUserId//商家ID
                        };
            if (!string.IsNullOrWhiteSpace(input.TravelName))
            {
                query = query.Where(c => c.TravelName.Contains(input.TravelName));
            }
            if (input.StartTime.HasValue && !input.StartTime.ToString().StartsWith("1991") && input.EndTime.HasValue && !input.StartTime.ToString().StartsWith("1991"))
            {
                query = query.Where(c => c.CreatedTime > input.StartTime && c.CreatedTime < input.EndTime);
            }
            if (input.SellerUserId.HasValue)
            {
                query = query.Where(c => c.SellerUserId == input.SellerUserId);
            }

            if (input.LoginUserId.HasValue)
            {
                query = query.Where(c => c.CreatedUserId == input.LoginUserId);
            }
            result.Total = query.Count();

            //分页
            var list = query.OrderByDescending(c => c.CreatedTime).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).Select(c => new OrderDto
            {
                Id = c.Id,
                CreatedTime = c.CreatedTime.Value,
                CreatedUserId = c.CreatedUserId,
                TotalPrice = c.Price,
                TravelName = c.TravelName,
            }).ToList();

            if ( list.Any())
            {
                var detail = TravelContext.TabOrderDetails.Where(c => list.Select(order => order.Id).Contains(c.OrderId));
                var users = await TravelContext.TabUsers.Where(c => list.Select(s => s.CreatedUserId).Contains(c.Id)).ToDictionaryAsync(c => c.Id);
                foreach (var item in list)
                {
                  var tabOrderDetails=  detail.Where(c => c.OrderId == item.Id).ToList();
                    item.TotalPrice += tabOrderDetails.Count() * item.TotalPrice;
                    item.FriendList = ObjectMapper.Map<List<OrderDetail>>(tabOrderDetails);
                    item.UserName = users[item.CreatedUserId].Username;
                }
            }
            result.Data = list;
            return Results<PageDto<OrderDto>>.DataResult(result);
        }
    }
}
